package com.sn.springboot_netty.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author fyy
 * @Description
 * @Date 2020/5/28 17:02
 */
public class ZipUtil {

    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    public static boolean folderToZip(String sourceFilePath, String zipFilePath, String fileName) {
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if (sourceFile.exists()) {
            try {
                File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
                if (!zipFile.exists()) {
                    File[] sourceFiles = sourceFile.listFiles();
                    if (null != sourceFiles && sourceFiles.length >= 1) {
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
                            // 创建ZIP实体，并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            zos.putNextEntry(zipEntry);
                            // 读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024 * 10);
                            int read = 0;
                            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                                zos.write(bufs, 0, read);
                            }
                        }
                        flag = true;
                    } else {
                        logger.error("待压缩的文件目录：" + sourceFilePath + "里面不存在文件,无需压缩");
                    }
                } else {
                    logger.error(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件");
                }
            } catch (Exception e) {
                logger.error("压缩的文件异常：{}",e.getMessage());
            } finally {
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.close();
                } catch (IOException e) {
                    logger.error("压缩的文件流关闭异常：{}",e.getMessage());
                }
            }
            FileUtil.delFolder(sourceFile); //删除文件夹
        }
        return flag;
    }


}
